package br.ifpi.leds.educmanager.control.converters;

import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.ifpi.leds.educmanager.model.Professor;

@FacesConverter(value = "professorConverter", forClass = Professor.class)
public class ProfessorConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
		if (value != null) {
            return this.getAttributesFrom(component).get(value);
        }
        return null;
	}

	@Override
	public String getAsString(FacesContext ctx, UIComponent component, Object value) {
		 if (value != null && ! "".equals(value)) {
	            Professor entity = (Professor) value;
	 
	            if (entity.getId() != null) {
	                this.addAttribute(component, entity);
	 
	                if (entity.getId() != null) {
	                    return String.valueOf(entity.getId());
	                }
	                return (String) value;
	            }
	        }
	        return "";
	}
	
	private void addAttribute(UIComponent component, Professor o) {
        this.getAttributesFrom(component).put(o.getId().toString(), o);
    }
 
    private Map<String, Object> getAttributesFrom(UIComponent component) {
        return component.getAttributes();
    }

}
